<?php

/**
 * ApplicationBehavior class
 *
 * @author Julot <andy.julot@gmail.com>
 * @since Monday, January 30, 2012. 02:39 PM
 */
class ApplicationBehavior extends CBehavior {

	public function events() {
		$data = array('onBeginRequest'=>'beginRequest');
		return array_merge(parent::events(), $data);
	}

	public function beginRequest() {
		$owner = $this->owner;
		if (isset($_GET['_theme'])) {
			$owner->user->setState('theme', $_GET['_theme']);
		}
		if ($owner->user->getState('theme')) {
			$owner->theme = $owner->user->getState('theme');
		} else {
			$owner->theme = $this->_selectTheme();
		}
	}

	protected function _selectTheme() {
		$browsers = array(
			'nokia', 'iphone', 'android', 'motorola', '^mot\-', 'softbank',
			'foma', 'docomo', 'kddi', 'up\.browser', 'up\.link', 'htc', 'dopod',
			'blazer', 'netfront', 'helio', 'hosin', 'huawei', 'novarra',
			'CoolPad', 'webos', 'techfaith', 'palmsource', 'blackberry',
			'alcatel', 'amoi', 'ktouch', 'nexian', 'samsung', '^sam\-',
			's[cg]h', '^lge', 'ericsson', 'philips', 'sagem', 'wellcom',
			'bunjalloo', 'maui', 'symbian', 'smartphone', 'midp', 'wap',
			'phone', 'windows ce', 'iemobile', '^spice', '^bird', '^zte\-',
			'longcos', 'pantech', 'gionee', '^sie\-', 'portalmmm',
			'jig\s browser', 'hiptop', '^ucweb', '^benq', 'haier', '^lct',
			'opera\s*mobi', 'opera\*mini', '320x320', '240x320', '176x220',
		);
		$mobileBrowser = '/(' . implode('|', $browsers) . ')/i';
		$mobilePatform = '/blackberry/i';

		$theme = 'coolblack';
		$browser = Yii::app()->browser->getBrowser();
		if (preg_match($mobileBrowser, $browser)) {
			$theme = 'mobile';
		} else {
			$platform = Yii::app()->browser->getPlatform();
			if (preg_match($mobilePatform, $platform)) {
				$theme = 'mobile';
			}
		}
		return $theme;
	}

}
